//
//  RemindMeController.swift
//  ANOA
//
//  Created by 邱仙凯 on 2021/3/2.
//  Copyright © 2021 aowang. All rights reserved.
//

import UIKit

class RemindMeController: BaseTableViewController {
    
    private var dataArray = [ToDoModel]()
    var callSegMentSetItem:((Bool)->())?
    var vou_no = ""
    var readed = "0"
    
    // 是否开启批量
    private var isBatch = false
    // 批量已阅
    private var isBatchReaded = false
    // 批量评论
    private var isBatchComment = false
    // 批量操作的 view
    private var batchView: RemindMeBatchView?
    
    private var batchModels: [ToDoModel]?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.network()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        title = "抄送"
   
        configFilter()
        // 渔美康批量操作: http://59.59.58.36:3316/zentao/task-view-23093.html
        if PlatformManager.shared.platform == .yuMeiKang {
            let batchBtn = UIBarButtonItem(title: "批量操作", style: .plain, target: self, action: #selector(batchBtnClick))
            navigationItem.rightBarButtonItem = batchBtn
        }
    }
    
    
    func configFilter() {

        var t1 = TemplateModel(JSON:["":""])!
        t1.isFormSHow = "1"
        t1.isFilterShow = "1"
        t1.field_nm = "readed_nm"
        t1.field_annotation = "排序"
        t1.default_value = "未读"
        t1.field_type = TemplateType.localSelect.rawValue
        t1.select_data = "0:未读,1:已读"
        t1.select_field_backfill = "readed,readed_nm"
 
        var t11 = TemplateModel(JSON:["":""])!
        t11.isFormSHow = "0"
        t11.isFilterShow = "0"
        t11.field_nm = "readed"
        t11.default_value = readed
        t11.field_type = TemplateType.input.rawValue
        
        let t2 = inputTypeFilter(nm: "关键字", param: "keyword")
     
        let temf = checkPlatform(type: .zhuYouAn) ? [t_begin_dt, t_end_dt, t2] : [t_begin_dt, t_end_dt, t1, t11, t2]
 
 
        let yyy = getTopH() + comSearchBanner.ks_height
 
        self.comSearchBanner.initWithFcontent(startY:yyy,templateFilter: temf)
        self.comSearchBanner.bannerComfirmClo = { [weak self] in
            
            guard let `self` = self else {
                return
            }
                        
            if let isrefresh = self.tableView.mj_header?.isRefreshing,isrefresh {
                self.tableView.mj_header?.endRefreshing()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                    self.tableView.mj_header?.beginRefreshing()
                }
            }  else {
                self.tableView.mj_header?.beginRefreshing()
            }
        }
    }

    
    //MARK: - TableView DataSource && Delegate
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let one = self.dataArray[indexPath.row]
        guard let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as? GlobalTableViewCell else {
           fatalError()
        }
        
        var titleAndStatus: (String, String)
        
        if checkPlatform(type: .zhuYouAn) {
            titleAndStatus = ("\(one.vocNm.unwrap)","")
        } else {
            let rss = one.readed.unwrap == "1" ? "已读" : "未读"
            titleAndStatus = ("\(one.vocNm.unwrap)","\(rss)")
        }
        
  
        var contArr:[(String,String?)]
      
            contArr = [
                ("",one.vouMemo.unwrap)
            ]

    
        cell.cellSelectable = isBatch
        cell.setDataSource(contentArr: contArr, titleAndStatus: titleAndStatus, isSelected: one.isSelected)

          
        return cell
        
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        var newOne = self.dataArray[indexPath.row]
        
        // 在批量操作的时候点击不跳转
        if isBatch {
            newOne.isSelected = !newOne.isSelected
            dataArray.replaceSubrange(indexPath.row..<indexPath.row + 1, with: [newOne])
            tableView.reloadData()
            return
        }
   
        if checkPlatform(type: .zhuYouAn) {
            /**
             新友安云修复【知会】中，差旅费、费用报销、借款 底部没有按钮
                解决方案: todoType 为 remind, 然后在具体的页面处理
             */
            newOne.todoType = "3"
        }
        let jsTT:JueseTypeEnum = newOne.readed.unwrap == "1" ? .commenter : .noticer
        go2AuditForm(newOne, controller: self,jueseType: jsTT)
        
    }

    //MARK: - Request
    override func network() {
       
        startDate = any2Str(comSearchBanner.filterV?.filterDic["begin_dt"])
        endDate = any2Str(comSearchBanner.filterV?.filterDic["end_dt"])
        vou_no = any2Str(comSearchBanner.filterV?.filterDic["keyword"])
        readed = any2Str(comSearchBanner.filterV?.filterDic["readed"])

        var api: API?
      
        api = API.auditFlow(.getAdmNoticeEvent(voc_cd: "", vou_no: vou_no, begin: startDate, end: endDate,readed: readed,page: "\(self.page)",size: "\(KSGlobal.pageSize)"))
         
        KSNetwork.shared.doRequest(api!, showHud: false) { [weak self] (data:BaseResult<ToDoModel>) in
            guard let `self` = self else {
                return
            }
            
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    
                    self.dataArray += infos
                    self.tableView.mj_header?.endRefreshing()
                    self.tableView.reloadData()
                    
                    if infos.count < KSGlobal.pageSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()

                    } else {
                        self.tableView.mj_footer?.endRefreshing()

                    }
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    /// 批量评论
    /// - Parameters:
    ///   - ids: 选中的数据 id
    ///   - text: 评论内容
    private func doBatchComment(text: String, complete: @escaping (() -> Void)) {
        if PlatformManager.shared.platform == .yuMeiKang {
            
            SVProgressHUD.show()
            
            if self.batchModels?.count ?? 0 > 0 {
                let model = self.batchModels!.first!
                doComment(model: model, comment: text) { [weak self] isSuccess, doModel in
                    
                    self?.batchModels?.removeFirst()
                    
                    if self?.batchModels?.count ?? 0 > 0 {
                        self?.doBatchComment(text: text, complete: complete)
                    } else {
                        SVProgressHUD.dismiss()
                        complete()
                    }
                }
            }
        }
    }
    
    private func doComment(model: ToDoModel, comment: String, complete: @escaping ((Bool ,ToDoModel?) -> Void)) {
        KSNetwork.shared.doRequest(API.auditFlow(.wflowhander(voc_cd: "", vou_id: "", instanceId: model.instanceId.unwrap, taskId: model.taskId.unwrap, nodeId: model.nodeId.unwrap, signature: "", agree: "comment", comment: comment, targetNode: "", targetUser: "", formData: "", formArray: "", otherNodeUsers: "", file: []))) { (data:BaseResult<OperateResult>) in
            
            if data.flag == TRUE {
                complete(true, nil)
                
            } else {
                complete(false, model)
            }
        }
    }
    
    /// 批量已阅
    /// - Parameter ids: 选中的数据 id
    private func doBatchRead(ids: [String], success: @escaping (() -> Void)) {
        if PlatformManager.shared.platform == .yuMeiKang {
            
            SVProgressHUD.show()
            
            var idsStr = ""
            for one in ids {
                idsStr.append("\(one),")
            }
            
            if idsStr.hasSuffix(",") {
                idsStr = idsStr.subTo(idsStr.count - 1)
            }
            
            KSNetwork.shared.doRequest(API.auditFlow(.updateCCread(instanceId: idsStr))) { (data:BaseResult<TodoResult>) in
                
                SVProgressHUD.dismiss()
                
                if data.status == "200" {
                    success()
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }
    }
    
    //MARK: - Button Click
    @objc func batchBtnClick() {
        if PlatformManager.shared.platform == .yuMeiKang {
            
            if dataArray.count == 0 {
                KSToast("当前无数据!")
                return
            }
            
            let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
            
            let commentAction = UIAlertAction(title: "批量评论", style: .default) { _ in
                self.isBatch = true
                self.isBatchComment = true
                self.isBatchReaded = false
                self.tableView.reloadData()
                
                let closeBatchBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(self.escBatchBtnClick))
                self.navigationItem.rightBarButtonItem = closeBatchBtn
                
                self.showBatchView(type: .comment)
            }
            
            let readAction = UIAlertAction(title: "批量已阅", style: .default) { _ in
                self.isBatch = true
                self.isBatchReaded = true
                self.isBatchComment = false
                self.tableView.reloadData()
                
                let closeBatchBtn = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(self.escBatchBtnClick))
                self.navigationItem.rightBarButtonItem = closeBatchBtn

                self.showBatchView(type: .readed)
            }
            
            let cancelAction = UIAlertAction(title: "取消", style: .cancel)
            
            alert.addAction(commentAction)
            alert.addAction(readAction)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
        }
    }
    
    private func showBatchView(type: RemindMeBatchType) {
        self.batchView = RemindMeBatchView.make(type: type, complete: { [unowned self] viewType, commentText in
            
            let selectModels = self.dataArray.filter({ $0.isSelected })
            
            if selectModels.count == 0 {
                var typeText = "已阅"
                if viewType == .comment {
                    typeText = "评论"
                }
                KSToast("请选择需要\(typeText)的单据")
                return
            }
            
            if viewType == .comment {
                
                if commentText?.count == 0 {
                    KSToast("请输入评论意见")
                    return
                }
                
                self.batchModels = selectModels
                self.doBatchComment(text: commentText ?? "") {
                    self.escBatchBtnClick()
                    self.tableView.setContentOffset(.zero, animated: false)
                    self.network()
                }
            } else {
                
                let ids = selectModels.compactMap({ return $0.instanceId.unwrap })
                
                self.doBatchRead(ids: ids) {
                    self.escBatchBtnClick()
                    self.tableView.setContentOffset(.zero, animated: false)
                    self.network()
                }
            }
        })
        
        self.view.addSubview(self.batchView!)
        self.batchView!.frame = CGRect(origin: .init(x: 0, y: self.view.ks_height), size: self.batchView!.ks_size)
        
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.3) {
                self.batchView?.ks_y = self.view.ks_height - self.batchView!.ks_height
            }
        }
    }
    
    private func dismissBatchView() {
        
        dataArray = dataArray.compactMap({ one in
            var newOne = one
            newOne.isSelected = false
            return newOne
        })
        
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.3) {
                self.batchView?.ks_y = KS_SCREEN_HEIGHT
            } completion: { _ in
                self.batchView?.removeFromSuperview()
                self.batchView = nil
            }
        }
    }
    
    @objc func escBatchBtnClick() {
        self.isBatch = false
        self.isBatchReaded = false
        self.isBatchComment = false
        self.tableView.reloadData()
        
        let batchBtn = UIBarButtonItem(title: "批量操作", style: .plain, target: self, action: #selector(batchBtnClick))
        navigationItem.rightBarButtonItem = batchBtn
        
        if PlatformManager.shared.platform == .yuMeiKang {
            self.dismissBatchView()
        }
    }
}

 
